import LimitPromise from "./LimitPromise";

/**
 * 加载js文件的工具
 */
export default class LoadScriptUtils {
  static loadScript(src: string, version: string | number) {
    return new Promise<void>(function (resolve, reject) {
      const script = document.createElement('script');
      script.src = src + '?_v=' + version;
      script.onload = function () {
        resolve();
      };
      script.onerror = function () {
        reject();
      };
      document.head.appendChild(script);
    });
  }

  /**
   * 串行加载全部js文件以后执行方法
   * var scripts = ['script1.js', 'script2.js', 'script3.js'];
   *        loadScriptsSequentially(scripts)
   *            .then(function() {
   * 							console.log('All scripts loaded successfully.');
   * 						})
   *            .catch(function() {
   * 							console.error('Failed to load one or more scripts.');
   * 						});
   * @param scripts
   * @param version
   */
  static loadScriptsSequentially(scripts: string[], version: string | number) {
    let limitPromise = new LimitPromise()
    const promises = scripts.map((script) => {
      return limitPromise.call(() => {
        return LoadScriptUtils.loadScript(script, version)
      })
    });
    return Promise.all(promises)
  }

  /**
   * 合并js加载
   */
  static mergeJsFileLoading(scripts: string[], version: string | number) {
    let jsContent = []
    scripts.forEach(i => {
      const xhr = new XMLHttpRequest();
      xhr.open('GET', i + '?_v=' + version, false); // 发送异步请求
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          if (xhr.status >= 200 && xhr.status < 300) {
            let responseText = xhr.responseText
            if (responseText) {
              jsContent.push(...responseText.split('\n'))
            }
          } else {
            xhr.status
          }
        }
      };
      xhr.send(null);
    })
    const htmlScriptElement = document.createElement('script');
    htmlScriptElement.innerHTML=jsContent.join('\n')
    document.body.appendChild(htmlScriptElement)
  }
}
